import { useState, useEffect } from "react";
import { Modal, Popover, message, Empty, Radio, Space } from "antd";
import { QrcodeOutlined } from "@ant-design/icons";
import emitter from '@/events';
import { onlineService } from '@/components/ToolBar/toolbar';
// css
import styles from "@/styles/CommonPersonal.module.scss";
// api
import { myOrderDetail, myOrderCancelReason, myOrderCancel } from "@/api/personal";

const OrderItemDetail = ({ }) => {

  const [visible, setVisible] = useState(false);
  const [detail, setDetail] = useState({});

  const [disabled, setDisabled] = useState(false);
  const [reasons, setReasons] = useState([]);
  const [reason, setReason] = useState("");

  useEffect(() => {
    // 初始化，去掉所有events
    emitter.removeAllListeners(['openDetail']);
    // 添加event
    emitter.on('openDetail', (data) => {
      setDetail({});
      if(data){
        // 详情
        myOrderDetail(data.orderId).then((res) => {
          const { code, data } = res;
          if(code === 0 && data){
            setDetail({...data})
            // 原因
            myOrderCancelReason(data.goodsType).then(reason => {
              if(reason.code === 0 && reason.data){
                setReasons([...reason.data])
              }
            })
          }
        })
        setVisible(data.open);
      }
    })

    return function (){
      emitter.removeAllListeners(['openDetail'])
    }
  }, []);

  // 订单状态
  function orderStatus (status, type){
    if(status === 10) return '待支付';
    if(status === 11){
      if(type == 1 || type == 2 || type == 4) return '待出票';
      if(type == 7) return '待出单';
      if(type == 3 || type == 5) return '待确认';
    }
    if(status === 20){
      if(type == 1 || type == 2 || type == 4 || type == 5 || type == 7) return '待使用';
      if(type == 3) return '待入住';
    }
    if(status === 21) return '待取票';
    if(status === 31) return '部分使用';
    if(status === 40) {
      if(type == 1 || type == 2 || type == 4 || type == 5 || type == 7) return '已使用';
      if(type == 3) return '已入住';
    }
    if(status === 50) return '退款完成';
    if(status === 51) return '退款审核中';
    if(status === 52) return '退款中';
    if(status === 60) return '已完成';
    if(status === 70) return '已取消';
  }
  // 出票状态
  function showTicketStatus(status) {
    switch(status){
      case 10: return '待出票';
      case 11: return '待取票';
      case 12: return '出票失败';
      case 20: return '已出票';
      case 30: return '核销中';
      case 40: return '已核销';
      case 50: return '已退票';
      case 60: return '已过期';
      case 70: return '已取消';
    }
  }
  // 选择radio
  function onChangeRadio(e) {
    setReason(e.target.value)
  }
  // 取消订单
  function cancelOrder() {
    if(!reason){
      message.warn('请选择取消原因');
      return false
    }
    setDisabled(true);
    myOrderCancel({
      reason,
      orderId: detail.orderId
    }).then(res => {
      let { code } = res;
      if (code === 0) {
        message.success('已取消订单');
        location.reload();
      }
      setDisabled(false);
    })
  }

  // Component
  const showQrImg = function (data){
    return (
      <div className={styles["order-qr-img"]}>
        <img src={data.qrImg} />
        <p>票号：{data.ticketNo || data.thirdTicketNo || '--'}</p>
      </div>
    )
  }

  // Component：取消订单，原因
  const cancelReasons = (
    <div className={styles['order-cancel-reason']}>
      <h4>取消订单原因</h4>
      <Radio.Group onChange={onChangeRadio}>
        <Space direction="vertical">
          {
            reasons.map(item => <Radio key={item.key} value={item.value}>{item.value}</Radio>)
          }
        </Space>
      </Radio.Group>
      <p><button disabled={disabled} onClick={() => { cancelOrder() }}>确定</button></p>
    </div>
  )

  return (
    <Modal className="no-footer" centered visible={visible} onCancel={() => { setVisible(false) }}>
      {
        detail.orderId ?
        <div className={styles["order-modal-detail"]}>
          <h2>{detail.orderName}</h2>
          {/* 订单状态 */}
          <div className={styles["status"]}>
            <h3>{orderStatus(detail.orderStatus, detail.goodsType)}</h3>
            { detail.orderStatus === 70 ? <p>您的订单已取消，祝您旅途愉快！</p> : ''}
            { detail.orderStatus === 10 ? <p>为保障您的出行权益，建议您尽快支付该订单！</p> : ''}
          </div>
          {/* 已付款，票号，二维码 */}
          {
            detail.orderStatus === 20 && detail.appletOrderItemInfoDTOS && detail.appletOrderItemInfoDTOS.length ?
            <div className={styles["qrcode"]}>
              <ul>
                {
                  detail.appletOrderItemInfoDTOS.map(item => {
                    const { appletOrderGoodsInfoDTOS } = item;
                    return appletOrderGoodsInfoDTOS.map((item1, index1) => {
                      return (
                        <li key={index1}>
                          <div>{item.skuName}</div>
                          <div>票号 {item1.ticketNo || item1.thirdTicketNo || "--"}</div>
                          <div>{showTicketStatus(item1.bizStatus)}</div>
                          <div>
                            <Popover placement="bottomRight" trigger="click" content={showQrImg(item1)}>
                              <QrcodeOutlined />
                            </Popover>
                          </div>
                        </li>
                      )
                    })
                  })
                }
              </ul>
            </div> : ""
          }
          {/* 订单详情信息 */}
          <div className={styles["info"]}>
            <p><span>订单编号</span>{detail.orderNo}</p>
            <p><span>下单时间</span>{detail.createTime}</p>
            <p>
              <span>支付方式</span>
              {
                detail.payWay == 1 ? '在线-微信支付' : (detail.payWay == 2 ? '在线-支付宝支付' : '在线-云闪付支付')
              }
            </p>
            { // 已支付
              (detail.orderStatus >= 20 && detail.orderStatus <= 60) ? <p><span>支付时间</span>{detail.payTime}</p> : ''
            }
            <p className={styles["price"]}><span>订单金额</span><i>￥</i><em>{detail.totalPay}</em></p>
            <p className={styles["price"]}><span>实付金额</span><i>￥</i><em>{detail.realPay}</em></p>
            { // 优惠金额
              detail.reducedPay ? <p className={styles["price"]}><span>优惠金额</span><i>-￥</i><em>{detail.reducedPay}</em></p> : ''
            }
            { // 优惠金额
              detail.voucherPay ? <p className={styles["price"]}><span>优惠金额</span><i>-￥</i><em>{detail.voucherPay}</em></p> : ''
            }
          </div>
          { // 联系人/电话
            (detail.linkman || detail.linkmanPhone) ?
            <div className={styles["contact"]}>
              {
                detail.linkman ? <p><span>联系人</span>{detail.linkman}</p> : ''
              }
              {
                detail.linkmanPhone ? <p><span>联系电话</span>{detail.linkmanPhone}</p> : ''
              }
            </div> : ""
          }
          {/* 支付 */}
          <div className={styles["pay"]}>
            {/* <button className={styles["pay-btn"]}>立即支付</button> */}
            {
              detail.orderStatus === 10 ? 
              <Popover placement="rightBottom" trigger="click" content={cancelReasons}>
                <button className={styles['cancel']}>取消订单</button>
              </Popover> : ""
            }
            <button onClick={() => { onlineService(detail.orderName) }}>联系客服</button>
          </div>
        </div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无订单数据" />
      }
    </Modal>
  );
};

export default OrderItemDetail
